package com.zyf.service;

import cn.hutool.core.io.FileUtil;
import com.zyf.utils.StringUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理语音
 */
public class HandleSpeechService {
    /**
     * 处理字幕文件
     */
    public String handleSrt(String txtFile, String srtFilepath) throws Exception {
        //读取源文件
        List<String> srclist = getSrcTxt(txtFile);
        Map<Integer, String> srcMap = new HashMap<>();
        if (srclist == null || srclist.size() <= 0) {
            return "";
        }
        for (int i = 0; i < srclist.size(); i++) {
            srcMap.put(i, srclist.get(i));
        }
        //读取字幕文件并生成最终的字幕文件
        List<String> srtlist = getSrtByRegix(srtFilepath);
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = srtFilepath.replace(".srt", "_final.srt");
            writer = new FileWriter(finalsrt, false);
            writer.write("finalFile");
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 读取字幕文件并生成最新的字幕文件
     */
    private List<String> getSrtByRegix(String filepath) throws Exception {
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        List<String> result = new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文,如果是则判断长度
                if (isChinese(temp.substring(0, 1))) {
                    List<String> res = splitStr(temp);
                    if (res.size() > 0) {
                        result.addAll(res);
                    }

                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 处理字幕文件汉字
     */
    public String handleSrtByMulMethods(String txtFile, String srtFilepath) throws IOException {
        //读取源文件
        String srcContent = getSrcTxtByLine(txtFile);
        String reversedS = new StringBuffer(srcContent).reverse().toString();
        //读取字幕文件
        List<String> zimulist = getSrtFile(srtFilepath);
        Collections.reverse(zimulist);  // 使用Collections工具类翻转
        //倒序进行字符串的截取和添加,只处理除最后两行,可能涉及标题的书写
        List<String> newSrtList = new ArrayList<>();
        int totalline = zimulist.size();
        for (int i = 0; i < totalline; i++) {
            String srtRes = zimulist.get(i);
            //判断这一行最后一个字符是否是汉字
            int length = 0;
            if (!isChinese(srtRes.substring(srtRes.length() - 1))) {
                length = srtRes.length();
            } else {
                length = srtRes.length() + 1;
            }
            if (i < totalline - 2) {
                String realContent = reversedS.substring(0, length);
                realContent = new StringBuffer(realContent).reverse().toString();
                newSrtList.add(realContent);
                reversedS = reversedS.substring(length);
            }
        }
        //处理字幕文件的最后两行
        int lastDoublelineLength = zimulist.get(totalline - 1).length() + zimulist.get(totalline - 2).length();
        int srcConlenth = reversedS.length();
        if (srcConlenth - lastDoublelineLength == 1) {
            //处理倒数第二行
            String srtRes = zimulist.get(totalline - 2);
            //判断这一行最后一个字符是否是汉字
            int length = 0;
            if (!isChinese(srtRes.substring(srtRes.length() - 1))) {
                length = srtRes.length();
            } else {
                length = srtRes.length() + 1;
            }
            String realContent = reversedS.substring(0, length);
            realContent = new StringBuffer(realContent).reverse().toString();
            newSrtList.add(realContent);
            reversedS = reversedS.substring(length);
            //处理倒数第一行
            String lastsrtRes = zimulist.get(totalline - 1);
            int lastlength = lastsrtRes.length();
            String lastrealContent = reversedS.substring(0, lastlength);
            lastrealContent = new StringBuffer(lastrealContent).reverse().toString();
            newSrtList.add(lastrealContent);
        }
        if (srcConlenth - lastDoublelineLength == 2) {
            for (int i = 2; i > 0; i--) {
                String srtRes = zimulist.get(totalline - i);
                int length = srtRes.length();
                String realContent = reversedS.substring(0, length);
                realContent = new StringBuffer(realContent).reverse().toString();
                newSrtList.add(realContent);
                reversedS = reversedS.substring(length);
            }
        }
        //翻转字幕纯中文文件
        Collections.reverse(newSrtList);  // 使用Collections工具类翻转
        //读取字幕文件并生成最终的字幕文件
        String finalFile = getFinalContent(srtFilepath, newSrtList);
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = srtFilepath.replace(".srt", "_final.srt");
            writer = new FileWriter(finalsrt, false);
            writer.write(finalFile);
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 处理字幕文件汉字无标点符号,使用模型medium
     */
    public String handleSrtByNotPunctuation(String txtFile, String srtFilepath) throws Exception {
        //读取源文件
        String[] punctuation = {"。", "，", "、", "；", "：", "？", "！", "•", "."};
        List<String> punctuations = Arrays.asList(punctuation);
        String srcContent = getSrcTxtByLine(txtFile);
        String reversedS = new StringBuffer(srcContent).reverse().toString();
        int srclength = srcContent.length();
        int punctuationLength = 0;
        for (char singlestr : srcContent.toCharArray()) {
            if (punctuations.contains(singlestr)) {
                punctuationLength++;
            }
        }
        //读取字幕文件
        List<String> zimulist = getSrtFile(srtFilepath);
        int zimuLength = 0;
        int emptyLength = 0;
        for (String str : zimulist) {
            zimuLength = zimuLength + str.length();
            for (char singlestr : str.toCharArray()) {
                if (" ".equals(singlestr)) {
                    emptyLength++;
                }
            }
        }
        if (zimulist.size() == 1) {
            throw new RuntimeException("字幕文件生成有误,请检查");
        }
        Collections.reverse(zimulist);  // 使用Collections工具类翻转
        //倒序进行字符串的截取和添加,只处理除最后两行,可能涉及标题的书写
        List<String> newSrtList = new ArrayList<>();
        int totalline = zimulist.size();
        for (int i = 0; i < totalline; i++) {
            String srtRes = zimulist.get(i);
            //判断这一行最后一个字符是否是汉字
            int length = srtRes.length() + 1;
            String realContent = "";
            try {
                realContent = reversedS.substring(0, length);
                reversedS = reversedS.substring(length);
            } catch (Exception e) {
                realContent = reversedS.substring(0, reversedS.length());
                reversedS = reversedS.substring(reversedS.length());
            }
            realContent = new StringBuffer(realContent).reverse().toString();
            newSrtList.add(realContent);
        }
        //翻转字幕纯中文文件
        Collections.reverse(newSrtList);  // 使用Collections工具类翻转
        //读取字幕文件并生成最终的字幕文件
        String finalFile = getFinalContent(srtFilepath, newSrtList);
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = srtFilepath.replace(".srt", "_final.srt");
            writer = new FileWriter(finalsrt, false);
            writer.write(finalFile);
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 处理字幕文件汉字无标点符号,使用模型medium
     */
    public String createSrtBySilence(String txtFile, Map<Integer, String> silenceMap) throws Exception {
        //读取源文件
        String[] punctuation = {"。", "，", "、", "；", "：", "？", "！", "•", "."};
        List<String> punctuations = Arrays.asList(punctuation);
        List<String> srcContent = getTxtByLine(txtFile);
        //读取静音位置
        Map<Integer, String> resMap = new HashMap<>();
        for (int i = 0; i < srcContent.size(); i++) {
            resMap.put(i, silenceMap.get(i));
        }
        //生成srt文件
        StringBuffer buffer = new StringBuffer();
        int duration = 2500;
        String starttime = "00:00:02,500";
        for (int i = 0; i < srcContent.size(); i++) {
            buffer.append(i + 1);
            buffer.append("\n");
            buffer.append(starttime);
            buffer.append(" --> ");
            int endtime = Integer.valueOf(resMap.get(i));
            int localtime = duration + endtime;
            int time2 = 0;
            int time3 = 0;
            if (localtime >= 60000) {
                time2 = localtime / 60000;
                time3 = localtime % 60000;
            } else {
                time3 = localtime;
            }
            StringBuffer time3Buffer = new StringBuffer();
            buffer.append("00:");
            time3Buffer.append("00:");
            if (time2 < 10) {
                buffer.append("0" + time2);
                time3Buffer.append("0" + time2);
            } else {
                buffer.append(time2);
                time3Buffer.append(time2);
            }
            buffer.append(":");
            time3Buffer.append(":");
            String time3Str = time3 + "";
            if (time3 < 10000) {
                buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
                time3Buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
            } else {
                buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
                time3Buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
            }
            buffer.append("\n");
            buffer.append(srcContent.get(i));
            buffer.append("\n");
            buffer.append("\n");

            starttime = time3Buffer.toString();
        }
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = txtFile.replace(".txt", "_final.srt");
            File file = new File(finalsrt);
            if (file.exists()) {
                file.delete();
            }
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 处理古诗词字幕文件
     */
    public String createGSCSrtBySilence(String txtFile, Map<Integer, String> silenceMap) throws Exception {
        //读取源文件
        List<String> srcContent = getGSCTxtByLine(txtFile);
        //读取静音位置
        Map<Integer, String> resMap = new HashMap<>();
        for (int i = 0; i < srcContent.size(); i++) {
            resMap.put(i, silenceMap.get(i));
        }
        //生成srt文件
        StringBuffer buffer = new StringBuffer();
        int duration = 2500;
        String starttime = "00:00:02,500";
        for (int i = 0; i < srcContent.size(); i++) {
            buffer.append(i + 1);
            buffer.append("\n");
            buffer.append(starttime);
            buffer.append(" --> ");
            int endtime = Integer.valueOf(resMap.get(i));
            int localtime = duration + endtime;
            int time2 = 0;
            int time3 = 0;
            if (localtime >= 60000) {
                time2 = localtime / 60000;
                time3 = localtime % 60000;
            } else {
                time3 = localtime;
            }
            StringBuffer time3Buffer = new StringBuffer();
            buffer.append("00:");
            time3Buffer.append("00:");
            if (time2 < 10) {
                buffer.append("0" + time2);
                time3Buffer.append("0" + time2);
            } else {
                buffer.append(time2);
                time3Buffer.append(time2);
            }
            buffer.append(":");
            time3Buffer.append(":");
            String time3Str = time3 + "";
            if (time3 < 10000) {
                buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
                time3Buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
            } else {
                buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
                time3Buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
            }
            buffer.append("\n");
            buffer.append(srcContent.get(i));
            buffer.append("\n");
            buffer.append("\n");

            starttime = time3Buffer.toString();
        }
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = txtFile.replace(".txt", "_final.srt");
            File file = new File(finalsrt);
            if (file.exists()) {
                file.delete();
            }
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 处理字幕文件汉字无标点符号,使用模型medium
     */
    public String createSrtByFFmpegSilence(String txtFile, Map<Integer, String> silenceMap, int fontlength) throws Exception {
        String[] punctuation = {"。", "，", "、", "；", "：", "？", "！", "•", ".","—"};
        List<String> punctuations = Arrays.asList(punctuation);
        //读取源文件
        String srcContent = getSrcTxtByLine(txtFile);
        List<String> txtList = splitStrByRegex(srcContent);
        //读取静音位置
        Map<Integer, String> resMap = new HashMap<>();
            for (int i = 0; i < silenceMap.size(); i++) {
                resMap.put(i, silenceMap.get(i));
            }
        //生成srt文件
        StringBuffer buffer = new StringBuffer();
        int duration = 0;
        String starttime = "00:00:00,000";
        for (int i = 0; i < resMap.size(); i++) {
            buffer.append(i + 1);
            buffer.append("\n");
            buffer.append(starttime);
            buffer.append(" --> ");
            int endtime = Integer.valueOf(resMap.get(i));
            int localtime = duration + endtime;
            int time2 = 0;
            int time3 = 0;
            if (localtime >= 60000) {
                time2 = localtime / 60000;
                time3 = localtime % 60000;
            } else {
                time3 = localtime;
            }
            StringBuffer time3Buffer = new StringBuffer();
            buffer.append("00:");
            time3Buffer.append("00:");
            if (time2 < 10) {
                buffer.append("0" + time2);
                time3Buffer.append("0" + time2);
            } else {
                buffer.append(time2);
                time3Buffer.append(time2);
            }
            buffer.append(":");
            time3Buffer.append(":");
            String time3Str = time3 + "";
            if (time3 < 1000) {
                buffer.append("00" + "," + time3Str);
                time3Buffer.append("00" + "," + time3Str);
            } else if (time3 < 10000) {
                buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
                time3Buffer.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
            } else {
                buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
                time3Buffer.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
            }
            buffer.append("\n");
            //设置超过25个字符则进行换行
            //判断是否是最后一行,以静音位置为标准进行文件的生成
            if(silenceMap.size()<txtList.size()){
                if(i==silenceMap.size()-1){
                    String content="";
                    for(int index=i;index<txtList.size();index++){
                        content=content+txtList.get(index);
                    }
                    generateLineByContent(buffer, content, fontlength, punctuations);
                }else{
                    String content = txtList.get(i);
                    generateLineByContent(buffer, content, fontlength, punctuations);
                }
            }else{
                String content = txtList.get(i);
                generateLineByContent(buffer, content, fontlength, punctuations);
            }
            buffer.append("\n");
            buffer.append("\n");

            starttime = time3Buffer.toString();
        }
        //写入文件
        FileWriter writer = null;
        try {
            String finalsrt = txtFile.replace(".txt", "_final.srt");
            File file = new File(finalsrt);
            if (file.exists()) {
                file.delete();
            }
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

    }

    /**
     * 处理字幕文件时间推移同时添加间隔时间
     */
    public String handleSrtByDuration(String srtFilepath, int duration) throws Exception {
        int realDuration = duration * 1000 + 500;
        //读取字幕文件
        InputStream inputstream = new FileInputStream(new File(srtFilepath));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文,如果是则判断长度
                if (!isChinese(temp.substring(0, 1)) && temp.length() > 5) {
                    String[] times = temp.split("-->");
                    int index = 0;
                    for (String str : times) {
                        String[] resTimes = str.trim().split(":");
                        int time2 = Integer.valueOf(resTimes[1]);
                        int time3 = Integer.valueOf(resTimes[2].replace(",", ""));
                        int time3AndDutation = time3 + realDuration;
                        if (time3AndDutation > 60000) {
                            time2++;
                            time3 = time3AndDutation - 60000;
                        } else {
                            time3 = time3AndDutation;
                        }
                        buffer_final.append(resTimes[0]);
                        buffer_final.append(":");
                        if (time2 < 10) {
                            buffer_final.append("0" + time2);
                        } else {
                            buffer_final.append(time2 + "");
                        }
                        buffer_final.append(":");
                        String time3Str = "" + time3;
                        if (time3 < 10000) {
                            buffer_final.append("0" + time3Str.substring(0, 1) + "," + time3Str.substring(1));
                        } else {
                            buffer_final.append(time3Str.substring(0, 2) + "," + time3Str.substring(2));
                        }
                        if (index == 0) {
                            buffer_final.append(" --> ");
                        }
                        index++;
                    }
                    buffer_final.append("\n");
                    num++;
                } else {
                    if (isChinese(temp.substring(0, 1))) {
                        buffer_final.append(temp);
                        buffer_final.append("\n");
                    } else {
                        if (temp.length() < 5) {
                            buffer_final.append("\n");
                        }
                        buffer_final.append(temp);
                        buffer_final.append("\n");
                    }
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //写入文件
        FileWriter writer = null;
        String finalsrt = "";
        try {
            finalsrt = srtFilepath.replace(".srt", "_final.srt");
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer_final.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }

    /**
     * 读取源文件
     */
    private String getSrcTxtByLine(String filepath) throws FileNotFoundException {
        String[] punctuation = {"。", "，", "、", "；", "：", "？", "！", "•", "."};
        List<String> punctuations = Arrays.asList(punctuation);
        StringBuffer buffer = new StringBuffer();
        InputStream inputstream = null;
        BufferedReader reader = null;
        String temp = "";
        try {
            inputstream= new FileInputStream(new File(filepath));
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int index=0;
            while ((temp = reader.readLine()) != null) {
                if(index==1){
                    for(int i=0;i<temp.toCharArray().length;i++){
                        String currStr=temp.toCharArray()[i]+"";
                        if(i>1){
                            if(!isChinese(currStr)&&!punctuations.contains(currStr)){
                                buffer.append("，");
                            }else{
                                buffer.append(currStr);
                            }
                        }else{
                            if(isChinese(currStr)||punctuations.contains(currStr)){
                                buffer.append(currStr);
                            }
                        }
                    }
                    buffer.append("。");
                }else{
                    for(char strChar:temp.toCharArray()){
                        String currStr=strChar+"";
                        if(isChinese(currStr)||punctuations.contains(currStr)){
                            buffer.append(currStr);
                        }
                    }
                }
                index++;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 读取源文件
     */
    private List<String> getSrcTxt(String filepath) throws FileNotFoundException {
        List<String> srcTxtlist = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                List<String> res = splitStr(temp);
                if (res.size() > 0) {
                    srcTxtlist.addAll(res);
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return srcTxtlist;
    }

    private List<String> getTxtByLine(String filepath) throws Exception {
        List<String> srcTxtlist = new ArrayList<>();
        InputStream inputstream =null;
        BufferedReader reader = null;
        String temp = "";
        try {
            inputstream = new FileInputStream(new File(filepath));
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (temp.length() > 0) {
                    srcTxtlist.add(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return srcTxtlist;
    }

    /**
     * 获取古诗词原数据
     * @param filepath
     * @return
     * @throws Exception
     */
    private List<String> getGSCTxtByLine(String filepath) throws Exception {
        List<String> srcTxtlist = new ArrayList<>();
        InputStream inputstream =null;
        BufferedReader reader = null;
        String temp = "";
        try {
            inputstream = new FileInputStream(new File(filepath));
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int index=0;
            StringBuffer buffer=new StringBuffer();
            while ((temp = reader.readLine()) != null) {
                if (temp.length() > 0) {
                    if(index>1){
                        buffer.append(temp.trim());
                    }else{
                        srcTxtlist.add(temp.trim());
                    }
                }
                index++;
            }
            //断句
            String[] punctuation = {"。", "？", "！"};
            // 使用正则表达式的"|"作为"或"操作符来组合多个分隔符
            String regex = "[" + String.join("|", punctuation) + "]";
            // 使用split方法分割字符串
            String[] parts = buffer.toString().split(regex);
            for(String part:parts){
                srcTxtlist.add(part);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return srcTxtlist;
    }

    /**
     * 拆分字符串行
     *
     * @return
     */
    public List<String> splitStr(String text) {
        // 定义正则表达式，匹配逗号或分号
        String regex = "[；：？！，]";
        // 使用Pattern编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        // 使用matcher来查找字符串中所有匹配的项
        Matcher matcher = pattern.matcher(text);
        // 通过替换分隔符为空字符串来分割字符串
        String[] res = matcher.replaceAll("").split("\\s*");
        List<String> result = new ArrayList<>();
        // 打印分割后的结果
        for (String str : res) {
            if (str.trim().length() > 1) {
                result.add(str + "，");
            }
        }
        return result;
    }

    /**
     * 拆分字符串行
     *
     * @return
     */
//    public List<String> splitStrByRegex(String text) {
//        List<String> result = new ArrayList<>();
//        List<String> firstResCon= createStrByPuration( text, "：");
//        for(String str:firstResCon){
//            List<String> secondStrList= createStrByPuration( str, "？");
//            for(String secondStr:secondStrList){
//                List<String> threeList= createStrByPuration( secondStr, "！");
//                for(String threeStr:threeList){
//                    List<String> fourStrList= createStrByPuration( threeStr, "。");
//                    result.addAll(fourStrList);
//                }
//            }
//        }
//
//        return result;
//    }

    /**
     * 拆分字符串行
     *
     * @return
     */
    public List<String> splitStrByRegex(String text) {
        List<String> result = new ArrayList<>();
        List<String> secondStrList = createStrByPuration(text, "？");
        for (String secondStr : secondStrList) {
            List<String> threeList = createStrByPuration(secondStr, "！");
            for (String threeStr : threeList) {
                List<String> fourStrList = createStrByPuration(threeStr, "。");
                result.addAll(fourStrList);
            }
        }
        String lastr=result.remove(result.size()-1);
        lastr=lastr+"。";
        result.add(lastr);
        return result;
    }

    /**
     * 根据符号分离字符串
     *
     * @param text
     * @param puation
     * @return
     */
    private List<String> createStrByPuration(String text, String puation) {
        List<String> result = new ArrayList<>();
        String[] secondStrs = text.split(puation);
        for (int i = 0; i < secondStrs.length; i++) {
            String cont = secondStrs[i];
            if (i < secondStrs.length - 1) {
                cont = cont + puation;
            }
            result.add(cont);
        }

        return result;
    }


    /**
     * 读取字幕文件
     */
    private List<String> getSrtFile(String filepath) throws FileNotFoundException {
        List<String> zimuTxtlist = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文,如果是则判断长度
                if (isChinese(temp.substring(0, 1))) {
                    zimuTxtlist.add(temp);
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return zimuTxtlist;
    }

    /**
     * 读取字幕文件并生成最新的字幕文件
     */
    private String getfinalFileByLine(String filepath, Map<Integer, String> srcMap) throws FileNotFoundException {
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文,如果是则判断长度
                if (isChinese(temp.substring(0, 1))) {
                    String srcline = srcMap.get(num);
                    buffer_final.append(srcline);
                    buffer_final.append("\n");
                    buffer_final.append("\n");
                    num++;
                } else {
                    buffer_final.append(temp);
                    buffer_final.append("\n");
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer_final.toString();
    }

    /**
     * 读取字幕文件并生成最新的字幕文件
     */
    private String getfinalFile(String filepath, Map<Integer, String> srcMap) throws FileNotFoundException {
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文,如果是则判断长度
                if (isChinese(temp.substring(0, 1))) {
                    //自动生成的字幕文件默认标点逗号是英文符
                    int count = 0;
                    int index = temp.indexOf(",");
                    while (index != -1) {
                        count++;
                        index = temp.indexOf(",", index + 1);
                    }
                    int totalline = count + 1;
                    for (int i = 0; i < totalline; i++) {
                        String srcline = srcMap.get(num);
                        buffer_final.append(srcline);
                        buffer_final.append("\n");
                        num++;
                    }
                    buffer_final.append("\n");
                } else {
                    buffer_final.append(temp);
                    buffer_final.append("\n");
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer_final.toString();
    }

    /**
     * 读取字幕文件并生成最新的字幕文件
     */
    private String getFinalContent(String filepath, List<String> newSrtList) throws FileNotFoundException {
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            int num = 0;
            while ((temp = reader.readLine()) != null) {
                if ("".equals(temp)) {
                    continue;
                }
                //判断第一个字是否是中文
                if (isChinese(temp.substring(0, 1))) {
                    buffer_final.append(newSrtList.get(num));
                    buffer_final.append("\n");
                    buffer_final.append("\n");
                    num++;
                } else {
                    buffer_final.append(temp);
                    buffer_final.append("\n");
                }
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer_final.toString();
    }


    public boolean isChinese(String str) {
        boolean isChinese = true;
        for (char c : str.toCharArray()) {
            if (!Character.isIdeographic(c)) {
                isChinese = false;
                break;
            }
        }
        return isChinese;
    }

    /**
     * 根据txt文档生成待处理文件体系
     */
    public void createFolderByTXT(String txtFile) throws Exception {
        File back = new File(txtFile);
        List<File> sourceFile = FileUtil.loopFiles(back.getParent(), file -> file.isFile() && (file.getName().endsWith(".mp3") || file.getName().endsWith(".wav")));
        if (sourceFile == null || sourceFile.size() <= 0) {
            throw new RuntimeException("背景音乐不存在");
        }
        //创建一级文件夹
        String firstLevelFolder = txtFile.substring(0, txtFile.indexOf("."));
        File firstLevelFolderFile = new File(firstLevelFolder);
        if (!firstLevelFolderFile.exists()) {
            firstLevelFolderFile.mkdir();
        }
        //读取文本文件
        List<String> txtList = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        InputStream inputstream = new FileInputStream(new File(txtFile));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (!StringUtil.isBlank(temp.trim())) {
                    if (temp.trim().contains("*********")) {
                        txtList.add(buffer.toString());
                        buffer = new StringBuffer();
                    } else {
                        buffer.append(temp.trim());
                        buffer.append("\n");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //对文件批量处理
        String[] punctuation = {"。", "、", "；", "：", "？", "！", "•", ".", "，", "\n"};
        List<String> punctuations = Arrays.asList(punctuation);
        for (String str : txtList) {
            String folderName = "";
            String filename = str.substring(str.length() - 10, str.length());
            for (char name : filename.toCharArray()) {
                String nameStr = name + "";
                if (!punctuations.contains(nameStr)) {
                    if (folderName.length() > 3) {
                        break;
                    }
                    folderName = folderName + name;
                }
            }
            File newFolder = new File(firstLevelFolder + File.separator + folderName);
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            //复制背景音乐
            copyFile(sourceFile.get(0).getAbsolutePath(), newFolder.getAbsolutePath());
            //写入文件
            FileWriter writer = null;
            try {
                String finalpath = newFolder.getAbsolutePath() + File.separator + folderName + ".txt";
                writer = new FileWriter(finalpath, false);
                writer.write(str);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (writer != null) {
                    writer.flush();
                    writer.close();
                }
            }
        }
    }

    private void copyFile(String sourceFile, String desfolder) {
        // 源文件路径
        Path source = Paths.get(sourceFile);
        // 目标文件夹路径
        Path destinationDir = Paths.get(desfolder);
        // 目标文件路径
        Path destination = destinationDir.resolve(source.getFileName());
        try {
            // 确保目标文件夹存在
            Files.createDirectories(destinationDir);
            // 使用Files.copy()方法复制文件到目标文件夹
            Files.copy(source, destination);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据字体长度设置
     */
    public void createSrtByFontlength(String txtpath, int length) throws Exception {
        length = 16;
        String[] punctua = {"。", "、", "；", "：", "？", "！", "•", ".", "，"};
        List<String> punctuations = Arrays.asList(punctua);
        //读取文本文件
        List<String> txtList = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(txtpath));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (!StringUtil.isBlank(temp.trim())) {
                    txtList.add(temp.trim());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //根据长度截取每一行的数据
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < txtList.size(); i++) {
            String content = txtList.get(i);
            generateContent(buffer, content, txtList, i, length, punctuations);
        }
        //写入新文件
        FileWriter writer = null;
        try {
            String finalpath = txtpath.replace(".txt", "_split.txt");
            writer = new FileWriter(finalpath, false);
            writer.write(buffer.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
        //生成语音

    }

    /**
     * 递归操作一行的数据，并将末尾的值放到下一行
     *
     * @param buffer
     * @param txtList
     * @param i
     * @param length
     * @param punctuations
     */
    private void generateContent(StringBuffer buffer, String content, List<String> txtList, int i, int length, List<String> punctuations) {
        String subtemp = "";
        if (content.length() <= length) {
            //判断最后一个字符是否是标点符号
            String lastStr = content.substring(content.length() - 1, content.length());
            if (punctuations.contains(lastStr)) {
                buffer.append(content.trim());
                buffer.append("\n");
            } else {
                char[] totalChar = content.toCharArray();
                int index = 0;
                for (int m = totalChar.length - 1; m >= 0; m--) {
                    String punctuation = totalChar[m] + "";
                    if (punctuations.contains(punctuation)) {
                        index = m;
                        break;
                    }
                }
                if (index == 0) {
                    buffer.append(content.trim());
                    buffer.append("\n");
                } else {
                    buffer.append(content.substring(0, index + 1).trim());
                    buffer.append("\n");
                    subtemp = content.substring(index + 1);
                    if (i < txtList.size() - 1) {
                        String next = txtList.get(i + 1);
                        next = subtemp + txtList.get(i + 1);
                    }
                }
                return;
            }
        } else {
            //判断最后一个字符是标点符号还是汉字
            String subcontent = content.substring(0, length);
            String lastStr = subcontent.substring(length - 1, length);
            if (punctuations.contains(lastStr)) {
                buffer.append(subcontent.trim());
                buffer.append("\n");
                content = content.substring(length);
            } else {
                char[] totalChar = subcontent.toCharArray();
                int index = 0;

                for (int m = totalChar.length - 1; m >= 0; m--) {
                    String punctuation = totalChar[m] + "";
                    if (punctuations.contains(punctuation)) {
                        index = m;
                        break;
                    }
                }
                if (index == 0) {
                    buffer.append(subcontent.trim());
                    buffer.append("\n");
                    content = content.substring(subcontent.length());
                } else {
                    buffer.append(subcontent.substring(0, index + 1).trim());
                    buffer.append("\n");
                    content = content.substring(index + 1);
                }
            }
            //判断是否截取完
            generateContent(buffer, content, txtList, i, length, punctuations);

        }

    }

    /**
     * 递归操作一行的数据，并将末尾的值放到下一行
     *
     * @param buffer
     * @param length
     * @param punctuations
     */
    private void generateLineByContent(StringBuffer buffer, String content, int length, List<String> punctuations) {
        String subtemp = "";
        if (content.length() <= length) {
            //判断最后一个字符是否是标点符号
            String lastStr = content.substring(content.length() - 1, content.length());
            if (punctuations.contains(lastStr)) {
                buffer.append(content.trim());
                buffer.append("\n");
            } else {
                char[] totalChar = content.toCharArray();
                int index = 0;
                for (int m = totalChar.length - 1; m >= 0; m--) {
                    String punctuation = totalChar[m] + "";
                    if (punctuations.contains(punctuation)) {
                        index = m;
                        break;
                    }
                }
                if (index == 0) {
                    buffer.append(content.trim());
                    buffer.append("\n");
                } else {
                    buffer.append(content.substring(0, index + 1).trim());
                    buffer.append("\n");
                    subtemp = content.substring(index + 1);
                }
                return;
            }
        } else {
            //判断最后一个字符是标点符号还是汉字
            String subcontent = content.substring(0, length);
            String lastStr = subcontent.substring(length - 1, length);
            if (punctuations.contains(lastStr)) {
                buffer.append(subcontent.trim());
                buffer.append("\n");
                content = content.substring(length);
            } else {
                char[] totalChar = subcontent.toCharArray();
                int index = 0;

                for (int m = totalChar.length - 1; m >= 0; m--) {
                    String punctuation = totalChar[m] + "";
                    if (punctuations.contains(punctuation)) {
                        index = m;
                        break;
                    }
                }
                if (index == 0) {
                    buffer.append(subcontent.trim());
                    buffer.append("\n");
                    content = content.substring(subcontent.length());
                } else {
                    buffer.append(subcontent.substring(0, index + 1).trim());
                    buffer.append("\n");
                    content = content.substring(index + 1);
                }
            }
            //判断是否截取完
            generateLineByContent(buffer, content, length, punctuations);

        }

    }


}
